import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponse } from './response.dto';

@Injectable()
export class ResponseInterceptor<T>
  implements NestInterceptor<T, ApiResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ApiResponse<T>> {
    const httpContext = context.switchToHttp();
    const request = httpContext.getRequest();
    const path = request.originalUrl;

    return next.handle().pipe(
      map((data) => {
        const response = httpContext.getResponse();
        const statusCode = response.statusCode;

        // 根据状态码确定消息
        let message = '';
        switch (statusCode) {
          case 200:
            message = '请求成功';
            break;
          case 201:
            message = '创建成功';
            break;
          case 204:
            message = '删除成功';
            break;
          default:
            message = '请求处理成功';
        }

        // 处理特殊情况：如果返回的是纯字符串或数字，作为数据
        if (typeof data === 'string' || typeof data === 'number') {
          return new ApiResponse(statusCode, message, data, undefined, path);
        }

        // 处理登录接口的特殊返回格式
        if (data && data.access_token) {
          return new ApiResponse(statusCode, '登录成功', data, undefined, path);
        }

        // 处理点赞接口的特殊返回格式
        if (data && data.likes !== undefined && data.isLiked !== undefined) {
          return new ApiResponse(statusCode, '操作成功', data, undefined, path);
        }

        // 处理删除操作（返回void）
        if (data === undefined) {
          return new ApiResponse(
            statusCode,
            message,
            undefined,
            undefined,
            path,
          );
        }

        // 其他情况
        return new ApiResponse(statusCode, message, data, undefined, path);
      }),
    );
  }
}
